<?php

namespace app\common\model;

use app\service\MsgService;
use think\Db;

class User extends Base
{
    protected function initialize()
    {
        parent::initialize();
    }

    /* 检查refer_id 是否可以作为 uid的上级 */
    public static function checkRefer($uid, $refer_id)
    {
        if ($uid == $refer_id) {
            return false;
        }
        $userInfo = self::getOneById($uid);
        $r = self::getOne(['id' => $refer_id]);
        if (!$r) {
            return false;
        }
        if ($userInfo['mall_id'] != $r['mall_id']) {
            return false;
        }
        while ($r) {
            if (!$r['refer_id']) {
                break;
            }
            if ($r['refer_id'] == $uid) {
                return false;
            }
            $r = self::getOne(['id' => $r['refer_id']]);
        }
        return true;
    }

    /* 用户ID转公众号openid */
    public static function uid2openid($uid)
    {
        return Db::name('user_wechat')->where('uid', $uid)->value('openid');
    }

    /* 资金变动 */
    public static function changeMoney($uid, $type, $number, $content = '', $order = false, $other = false, $sid = 0)
    {
        if ($number == 0) {
            return false;
        }
        if ($uid) {
            $userInfo = self::getOne(['id' => $uid]);
        }
        if ($order && $order['sid']) {
            $sid = $order['sid'];
        }
        $log = [
            'uid' => $uid,
            'order_id' => $order ? $order['id'] : '',
            'type' => $type,
            'log_type' => $number > 0 ? 1 : 0,
            'money' => abs($number),
            'content' => $content,
            'mall_id' => isset($userInfo['mall_id']) ? $userInfo['mall_id'] : 1,
            'create_time' => time(),
            'update_time' => time(),
            'sid' => $sid
        ];
        if ($other) {
            if ($other['is_charge']) {
                $log['is_charge'] = 1;
            }
            if ($other['manager_name']) {
                $log['manager_name'] = $other['manager_name'];
            }
            if ($other['thumb']) {
                $log['thumb'] = $other['thumb'];
            }
            if ($other['is_has']) {
                $log['is_has'] = $other['is_has'];
            }
        }
        $res = MoneyLog:: setInsertGetId($log);
        if ($res) {
            switch ($type) {
                case 1:
                    self::where('id', $uid)->setInc('money', $number);
                    $yue = $userInfo['money'] + $number;
                    $name = config('site_yongjin_name');
                    break;
                case 2:
                    if ($log['sid']) {
                        Student::where('id', $log['sid'])->setInc('score', $number);
                        $yue = Student::getValue(['id' => $log['sid']], 'score');
                    } else {
                        self::where('id', $uid)->setInc('score', $number);
                        $yue = $userInfo['score'] + $number;
                    }
                    $name = config('site_score_name');
                    break;
                case 3:
                    self::where('id', $uid)->setInc('cash', $number);
                    $yue = $userInfo['cash'] + $number;
                    $name = config('site_cash_name');
                    $number *= 10;
                    break;
            }
            if ($uid) {
                $userInfo = self::getOne(['id' => $uid]);
                //TODO 资金变动消息
                $types = [
                    1 => '元',
                    2 => '积分',
                    3 => '抵扣金'
                ];
                $first = "变动账户:{$name}\n" . "变动金额:" . $number . $types[$type];
                MsgService::S(['mall_id' => $userInfo['mall_id']])->sendTemp('YUE', $userInfo['mall_id'], $userInfo['id'], [
                    'first' => $first,
                    'user_name' => $userInfo['nickname'],
                    'money' => (string)round($yue, 2),
                    'remark' => "备注:" . $content
                ]);
            }
        }
    }

    /* 上级第一个群主 */
    public static function getTopRefer($uid)
    {
        $referInfo = self::getOneById($uid);
        if ($referInfo['grade_id'] > 1) {
            return $referInfo;
        }
        while ($referInfo) {
            if (!$referInfo['refer_id']) {
                return false;
            }
            $referInfo = self::getOneById($referInfo['refer_id']);
            if ($referInfo['grade_id'] > 2) {
                return $referInfo;
            }
        }
        return false;
    }

    /* 群ID */
    public static function getGroupId($uid)
    {
        $userInfo = self::getOneById($uid);

        if (config('chat_type') == 2) {//子群模式
            $refer = self::getTopRefer($uid);
            if ($refer && $refer['chat_type'] == 2) {
                return $refer['mall_id'] . '-' . $refer['id'];
            }
            return $userInfo['mall_id'] . '-0';
        } else {
            return $userInfo['mall_id'];
        }

    }

    /* 判断是否是管理员 */
    public static function isManager($uid)
    {
        //全局配置的管理员
        if (in_array($uid, explode(',', config('chat_manager')))) {
            return true;
        }
        $userInfo = self::getOneById($uid);
        //分群模式下，群主即管理员
        if (config('chat_type') == 2 && $userInfo['chat_type'] == 2 && $userInfo['grade_id'] >= 2) {
            return true;
        }
        return false;
    }

    /* 判断是否是直播管理员 */
    public static function isLiveManager($uid)
    {
        if (in_array($uid, explode(',', config('live_manager')))) {
            return true;
        }
        return false;
    }

    /* 最近登陆的用户 */
    public static function getRencentList($uid)
    {
        $userInfo = self::getOneById($uid);
        if (config('chat_type') == 2) {//子群模式
            $refer = self::getTopRefer($uid);
            if ($refer && $refer['chat_type'] == 2) {
                $xiajiList = self::getTeamUserList($refer['id']);
                if (empty($xiajiList)) {
                    return [];
                }
                $recentList = Loginstatus::getAll([
                    'mall_id' => $userInfo['mall_id'],
                    'update_time' => [
                        'egt', time() - 3600 * 24
                    ],
                    'uid' => ['in', $xiajiList]
                ]);
            } else {
                /* $recentList = Loginstatus::getAll([
                    'mall_id' => $userInfo['mall_id'],
                    'update_time' => [
                        'egt',time()-3600*24
                    ]
                ]); */
                //没有上级的用户
                $uids = self::where([
                    'grade_id' => 1,
                    'refer_id' => 0
                ])->column('id');
                $recentList = Loginstatus::getAll([
                    'mall_id' => $userInfo['mall_id'],
                    'uid' => [
                        'in', $uids
                    ],
                    'update_time' => [
                        'egt', time() - 3600 * 24
                    ]
                ]);
            }
        } else {
            $recentList = Loginstatus::getAll([
                'mall_id' => $userInfo['mall_id'],
                'update_time' => [
                    'egt', time() - 3600 * 24
                ]
            ]);
        }
        return $recentList;
    }

    /* 获取团队所有用户 */
    public static function getTeamUserList($uid)
    {
        $uids = [];
        $info = self::getOneById($uid, 'refer_id,id,grade_id');
        $info['grade_id'] = 1;
        $list[] = $info;
        while (!empty($list)) {
            $xiajiUids = [];
            foreach ($list as $v) {
                if ($v['grade_id'] <= 1) {
                    $uids[] = $v['id'];
                    $xiajiUids[] = $v['id'];
                }
            }
            if (empty($xiajiUids)) {
                break;
            }
            $list = self::getAll([
                'refer_id' => ['in', $xiajiUids]
            ], '', 'refer_id,id,grade_id');
        }
        return $uids;
    }

    /* 获取上级第一个等级为x的用户
    self 是否包含本人
     */
    public static function getFirstRefer($uid, $grade, $self = true)
    {
        $referInfo = self::getOneById($uid);
        if ($grade == 4) {
            $grade = 1.5;//店长介于会员和代理商之间
        }
        $referInfo['grade_id'] = $referInfo['grade_id'] == 4 ? 1.5 : $referInfo['grade_id'];
        if ($self) {
            if ($referInfo['grade_id'] == $grade) {
                return $referInfo;
            }
            if ($referInfo['grade_id'] > $grade) {
                return false;
            }
        }
        while ($referInfo) {
            if (!$referInfo['refer_id']) {
                return false;
            }
            if ($referInfo['refer_id'] == $uid) {
                return false;
            }
            $referInfo = self::getOneById($referInfo['refer_id']);
            $referInfo['grade_id'] = $referInfo['grade_id'] == 4 ? 1.5 : $referInfo['grade_id'];
            /* if($referInfo['grade_id']>$grade) {
                 return false;
             }*/
            if ($referInfo['grade_id'] > $grade) {
                return false;
            }
            if ($referInfo['grade_id'] == $grade) {
                return $referInfo;
            }
        }
        return false;
    }
}